package top.hkyzf.study.leetcode.array;

import org.junit.Test;

import java.util.HashMap;
import java.util.Map;

/**
 * @author 朱峰
 * @date 2022-2-9 8:37
 */
public class 差的绝对值为K的数对数目_2006 {
    public int countKDifference1(int[] nums, int k) {
        int result = 0;
        for (int i = 0; i < nums.length; i++) {
            for (int j = i+1; j < nums.length; j++) {
                if (Math.abs(nums[i] - nums[j]) == k) {
                    result++;
                }
            }
        }
        return result;
    }

    public int countKDifference(int[] nums, int k) {
        Map<Integer, Integer> map = new HashMap<>();
        int result = 0;
        for (int num : nums) {
            result = result + map.getOrDefault(num + k, 0) + map.getOrDefault(num - k, 0);
            map.put(num, map.getOrDefault(num, 0) + 1);
        }
        return result;
    }

    @Test
    public void testCountKDifference () {
        int[] nums = {1,2,2,1};
        int k = 1;
        System.out.println(countKDifference(nums, k));
    }
}
